import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import { addCartAPI, getCartAPI, deleteCartAPI } from '@/apis/cart'
export const useCartStore = defineStore('cart',()=>{
    const userStore = useUserStore();
    const isLogin = computed(()=>userStore.userInfo.token);
    //购物车列表
    const cartList = ref([]);
    //更新购物车列表
    const updateCartList = async ()=>{
        const res = await getCartAPI();
        cartList.value = res.result
    }
    const addCart = async (goods)=>{
        const {skuId,count} = goods
        if(isLogin.value){
            //登录之后添加购物车
            await addCartAPI({skuId,count})
            updateCartList()
        }else{
            const item = cartList.value.find((item) => item.skuId === goods.skuId)
            //添加过count+添加的count;
            //没有添加过直接push
            if (item) {
                item.count = item.count + goods.count
            } else {
                cartList.value.push(goods)
            }
        }
    }
    //购物车删除功能
    const delCart =async (skuId) =>{
        if(isLogin.value){
            await deleteCartAPI([skuId])
            updateCartList()
        }else{
            const id = cartList.value.findIndex((item) => item.skuId === skuId)
            cartList.value.splice(id, 1);
        }
    }
    //清空购物车方法
    const clearCart = ()=>{
        cartList.value = [];
    }
    //计算总数量
    const allCount = computed(()=>cartList.value.reduce((a,c)=>a+c.count,0))
    //计算总价格
    const allPrice = computed(()=>cartList.value.reduce((a,c)=>a+c.count*c.price,0))
    //已选数量
    const checkCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    //已选价格
    const checkPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count*c.price, 0))
    //单选
    const singleCheck = (i,selected)=>{
        const item = cartList.value.find((item)=>item.skuId===i.skuId)
        item.selected = selected
    }
    //看是否全选
    const allSelected = computed(()=>cartList.value.every((item)=>item.selected))
    //全选
    const allCheck = (selected)=>{
        cartList.value.forEach((item)=>item.selected = selected)
    }
    return {
        cartList,
        allCount,
        allPrice,
        allSelected,
        checkCount,
        checkPrice,
        addCart,
        delCart,
        singleCheck,
        allCheck,
        clearCart,
        updateCartList
    }
},
    {
        persist: true,
    },)